package com.nanhai.buddhist.college.module.collegebase.controller.admin.professions;

import com.nanhai.buddhist.college.framework.common.pojo.CommonResult;
import com.nanhai.buddhist.college.framework.common.pojo.PageResult;
import com.nanhai.buddhist.college.framework.common.util.collection.CollectionUtils;
import com.nanhai.buddhist.college.framework.excel.core.util.ExcelUtils;
import com.nanhai.buddhist.college.framework.operatelog.core.annotations.OperateLog;
import com.nanhai.buddhist.college.module.collegebase.controller.admin.professions.vo.*;
import com.nanhai.buddhist.college.module.collegebase.convert.professions.ProfessionsConvert;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.classes.ClassesDO;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.departments.DepartmentsDO;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.professions.ProfessionsDO;
import com.nanhai.buddhist.college.module.collegebase.service.classes.ClassesService;
import com.nanhai.buddhist.college.module.collegebase.service.professions.ProfessionsService;
import com.nanhai.buddhist.college.module.system.api.user.AdminUserApi;
import com.nanhai.buddhist.college.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

import static com.nanhai.buddhist.college.framework.common.pojo.CommonResult.*;
import static com.nanhai.buddhist.college.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.nanhai.buddhist.college.module.collegebase.enums.ErrorCodeConstants.CLASSES_NOT_DELETE_XHUAN;

@Api(tags = "管理后台 - 学校管理--专业")
@RestController
@RequestMapping("/collegebase/professions")
@Validated
public class ProfessionsController {

    @Resource
    private ProfessionsService professionsService;

    @Resource
    private ClassesService classesService ;


    @Resource
    private AdminUserApi adminUserApi;
    @PostMapping("/create")
    @ApiOperation("创建学校管理--专业")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<String> createProfessions(@Valid @RequestBody ProfessionsCreateReqVO createReqVO) {
        return success(professionsService.createProfessions(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新学校管理--专业")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<Boolean> updateProfessions(@Valid @RequestBody ProfessionsUpdateReqVO updateReqVO) {
        professionsService.updateProfessions(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除学校管理--专业")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<Boolean> deleteProfessions(@RequestParam("id") String id) {

        List<ClassesDO> listDo = classesService.getClassesListByProfessionsId(id);
        if(listDo!=null && listDo.size()>0){
            return error(CLASSES_NOT_DELETE_XHUAN);
        }

        professionsService.deleteProfessions(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得学校管理--专业")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    public CommonResult<ProfessionsRespVO> getProfessions(@RequestParam("id") String id) {
        ProfessionsDO professions = professionsService.getProfessions(id);
        return success(ProfessionsConvert.INSTANCE.convert(professions));
    }

    @GetMapping("/list")
    @ApiOperation("获得学校管理--专业列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    public CommonResult<List<ProfessionsRespVO>> getProfessionsList(@RequestParam("ids") Collection<String> ids) {
        List<ProfessionsDO> list = professionsService.getProfessionsList(ids);
        return success(ProfessionsConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得学校管理--专业分页")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<PageResult<ProfessionsRespVO>> getProfessionsPage(@Valid ProfessionsPageReqVO pageVO) {
        PageResult<ProfessionsDO> pageResult = professionsService.getProfessionsPage(pageVO);

//        Set<String> strings = CollectionUtils.convertSet(pageResult.getList(), ProfessionsDO::getUserId);
//        Map<String, AdminUserRespDTO> longAdminUserRespDTOMap = new HashMap<>();
//        if (!strings.isEmpty()) {
//            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(strings);
//            longAdminUserRespDTOMap.putAll(CollectionUtils.convertMap(users.getData(), AdminUserRespDTO::getId));
//            pageResult.getList().forEach(item -> {
//                if (StringUtils.hasText(item.getUserId())) {
//                    item.setUserId(Optional.ofNullable(longAdminUserRespDTOMap).map(s -> s.get(item.getUserId())).map(AdminUserRespDTO::getNickname).orElse(""));
//                }
//            });
//        }
        return success(ProfessionsConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出学校管理--专业 Excel")
    @PreAuthorize("@ss.hasPermission('collegebase:professions:export')")
    @OperateLog(type = EXPORT)
    public void exportProfessionsExcel(@Valid ProfessionsPageReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<ProfessionsDO> list = professionsService.getProfessionsList(exportReqVO);

//        Set<String> strings = CollectionUtils.convertSet(list, ProfessionsDO::getUserId);
//        Map<String, AdminUserRespDTO> longAdminUserRespDTOMap = new HashMap<>();
//        if (!strings.isEmpty()) {
//            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(strings);
//            longAdminUserRespDTOMap.putAll(CollectionUtils.convertMap(users.getData(), AdminUserRespDTO::getId));
//            list.forEach(item -> {
//                if (StringUtils.hasText(item.getUserId())) {
//                    item.setUserId(Optional.ofNullable(longAdminUserRespDTOMap).map(s -> s.get(item.getUserId())).map(AdminUserRespDTO::getNickname).orElse(""));
//                }
//            });
//        }
        // 导出 Excel
        List<ProfessionsExcelVO> datas = ProfessionsConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "学校管理--专业.xls", "数据", ProfessionsExcelVO.class, datas);
    }


    @GetMapping("/byDepartments/list")
    @ApiOperation("获得专业列表")
    @ApiImplicitParam(name = "departmentsId", value = "系部id", required = true, example = "1024,2048", dataTypeClass = String.class)
    public CommonResult<List<ProfessionsRespVO>> getProfessionsList(@RequestParam("departmentsId") String departmentsId) {
        List<ProfessionsDO> list = professionsService.getProfessionsListByDepartmentsId(departmentsId);
        return success(ProfessionsConvert.INSTANCE.convertList(list));
    }


}
